/**
 * Created by jerome.arnoult on 19/05/14.
 */
function gamegui(){
    this.constructMode = false;
    this.destructMode = false;
    this.needCursor = false;
    this.mouseUp = true;
    this.initCellPos = {};
    this.initMousePos = {};
    this.initStagePosition = {};
    this.corridorPath = false;
    this.debug = debugGame || false;

    this.cursor1x1;
    
    this.currentConstruct;
    this.currentConstructPath = [];
    this.currentType;
    this.currentOrientation = "N";
    this.nbStructure = 0;

    this.initGui();
}

gamegui.prototype.initGui = function(){
    /**
     * Cursor
     */
//    document.onmousemove = function(evt){
//        var o = document.getElementById('cursor');
//        o.style.left = evt.clientX + 1 + "px";
//        o.style.top = evt.clientY + 1 + "px";
//    };

    /**
     * Build menu
     */
    var totalUl = 0;
    var widthLi;
    var windowWidth = parseInt($(".carousel-window").outerWidth());
    $('.carousel-window li').each(function(){
        if (widthLi == undefined) {
            widthLi = parseInt($(this).outerWidth())
        }
        totalUl += widthLi;
    });
    $('.carousel-window ul').css('width',totalUl+"px");
    $('.carousel-window ul').css('left', "0px");
    
    $('.buildMenuPrev').click(function(evt){
        evt.preventDefault();
        var currentLeft = parseInt($('.carousel-window ul').css('left'));
        if (currentLeft < 0) {
            $('.carousel-window ul').stop().animate({'left':(currentLeft+widthLi)+"px"},200);
        }
    });
    $('.buildMenuNext').click(function(evt){
        evt.preventDefault();
        var currentLeft = parseInt($('.carousel-window ul').css('left'));
        if (currentLeft > -(totalUl-windowWidth)) {
            $('.carousel-window ul').stop().animate({'left':(currentLeft-widthLi)+"px"},200);
        }
    });
    $('.carousel-window').bind('mousewheel DOMMouseScroll', function(evt){
        evt.preventDefault();
        if (evt.originalEvent.wheelDelta > 0 || evt.originalEvent.detail < 0) {
            var currentLeft = parseInt($('.carousel-window ul').css('left'));
            if (currentLeft < 0) {
                $('.carousel-window ul').stop().animate({'left':(currentLeft+widthLi)+"px"},200);
            }
        }else{
            var currentLeft = parseInt($('.carousel-window ul').css('left'));
            if (currentLeft > -(totalUl-windowWidth)) {
                $('.carousel-window ul').stop().animate({'left':(currentLeft-widthLi)+"px"},200);
            }
        }
    });
    
    /**
     * cursor 1x1
     */
    this.cursor1x1 = new createjs.Shape();
    this.cursor1x1.regX = 0;
    this.cursor1x1.regY = 0;
    this.cursor1x1.x = -1000;
    this.cursor1x1.y = 0;
    this.cursor1x1.graphics
        .moveTo(0, -8)
        .beginStroke('#ABABAB')
        .setStrokeStyle(0.5)
        .lineTo(-16, 0)
        .lineTo(0, 8)
        .lineTo(16, 0)
        .lineTo(0, -8)
        .endStroke();
    game.mainContainer.addChild(this.cursor1x1);
    
    /**
     * Need Some another cursor
     */
    
    
    /**
     * Activate link for construct
     */
    $("#panelConstruct ul a").on('click', function(evt){
        evt.preventDefault();
        var target=(evt.target.tagName=='A')
                ? evt.target
                : $(evt.target).closest('a')[0]
        var type = target.getAttribute('class');
        game.gameGui.startConstructMode(type, null);
    });


    //Debug
    if(this.debug === true){
        $.ajax(domainOriginGame+"debug.html").success(function(data){
            $("#debugBar").html(data)
            .dialog({
                appendTo:"#pageContainer",
                width:"200",
                height:"400",
                autoOpen:false,
                title: "Debug",
                modal:false,
                draggable:false,
                buttons:[],
                dialogClass: 'debugBar'
            });

            //debug player panel btn
            $("#panelPlayer .debugBtn").click(function(){
                if($('#debugBar').dialog("isOpen")){
                    $('#debugBar').dialog("close")
                }else{
                    $('#debugBar').dialog("open");
                    $('.debugBar').draggable({
                        containment:[0,0,window.innerWidth-208,window.innerHeight-400],
                        handle:'.ui-dialog-title'
                    })
                }
            });

            //Debug btns
            $("#debugBar .drawingToggleFPS").click(function(){
                game.gameDebug.drawingToggleFPS();
            });
            $("#debugBar .grillToggle").click(function(){
                game.gameDebug.gridToggle();
            });
            $("#debugBar .grillToggleCoords").click(function(){
                game.gameDebug.gridToggleCoords();
            });
            $("#debugBar .grillToggleAStarCoords").click(function(){
                game.gameDebug.gridToggleAStarCoords();
            });
            $("#debugBar .grillToggleExplorer").click(function(){
                game.gameDebug.gridToggleExplorer();
            });

        }).error(function(){
            $("#panelPlayer .debugBtn").hide();
        })
    }else
        $("#panelPlayer .debugBtn").hide();
    
}
gamegui.prototype.startConstructMode = function(type,initPos){
    if(this.constructMode)
        game.mainContainer.removeChild(game.gameGui.currentConstruct);
    this.constructMode = true;
    if(initPos == null){
        var initPos = [];
        initPos[0] = -10;
        initPos[1] = 0;
    }
    switch(type){
        case "corridor":
            game.gameGui.currentConstruct = game.gameRenderer.createCorridor(initPos[0], initPos[1], null);
            game.gameGui.currentType = type;
            break;
        case "extractor":
            game.gameGui.currentConstruct = game.gameRenderer.createExtractor(initPos[0], initPos[1], this.currentOrientation);
            game.gameGui.currentType = type;
            break;
        case "generator":
            game.gameGui.currentConstruct = game.gameRenderer.createGenerator(initPos[0], initPos[1], this.currentOrientation);
            game.gameGui.currentType = type;
            break;
        case "biodome":
            game.gameGui.currentConstruct = game.gameRenderer.createGarden(initPos[0], initPos[1], this.currentOrientation);
            game.gameGui.currentType = type;
            break;
        case "kitchen":
            game.gameGui.currentConstruct = game.gameRenderer.createKitchen(initPos[0], initPos[1], this.currentOrientation);
            game.gameGui.currentType = type;
            break;
        case "defenceArea":
            game.gameGui.currentConstruct = game.gameRenderer.createDefenceArea(initPos[0], initPos[1], this.currentOrientation);
            game.gameGui.currentType = type;
            break;
        
        default:
            console.log('Nooo je reconnais pas le type de construction : '+ type);
            this.constructMode = false;
            break;
    }
}
gamegui.prototype.placeConstruct = function(x, y){
    switch(game.gameGui.currentType){
        case "corridor":
            var next = game.gameGui.nbStructure;
            if(game.gameGui.constructPath != undefined){
                if(game.gameGui.constructPathError == false) {
                    for (var i in game.gameGui.constructPath) {
                        next = game.gameGui.nbStructure;
                        var gridCoords = game.gameMap.convertAStarCoordsToGridCoords(game.gameGui.constructPath[i]);
                        game.gameMap.structures["player0"][next] = new gamestructure("cor" + next, "corridor", {"thorium":1}, null, null, 10);
                        game.gameMap.structures["player0"][next].place(gridCoords[0] >> 0, gridCoords[1] >> 0, null, {"player": null});
                        game.gameGui.nbStructure++;
                    }
                }
            }else{
                game.gameMap.structures["player0"][next] = new gamestructure("cor"+next, "corridor", {"thorium":1}, null, null, 10);
                game.gameMap.structures["player0"][next].place(x>>0, y>>0, null, {"player":null});
                game.gameGui.nbStructure++;
            }
            break;
        
        case "extractor":
            var next = game.gameGui.nbStructure;
            //TODO : Choper le type de nuage de thorium a proximité pour savoir combien il produit
            game.gameMap.structures["player0"][next] = new gamestructure("ext"+next, "extractor", {"thorium":4}, {"thorium":4}, {"miner":1}, 30);
            game.gameMap.structures["player0"][next].place(x>>0, y>>0, game.gameGui.currentOrientation, {"player":null});
            game.gameGui.nbStructure++;
            break;
        case "generator":
            var next = game.gameGui.nbStructure;
            game.gameMap.structures["player0"][next] = new gamestructure("gen"+next, "generator", {"thorium":4}, {"energy":4}, {"engineer":1}, 30);
            game.gameMap.structures["player0"][next].place(x>>0, y>>0, game.gameGui.currentOrientation, {"player":null});
            game.gameGui.nbStructure++;
            break;
        case "biodome":
            var next = game.gameGui.nbStructure;
            game.gameMap.structures["player0"][next] = new gamestructure("bio"+next, "biodome", {"thorium":6}, {"harvest":4}, {"Harvester":2}, 40);
            game.gameMap.structures["player0"][next].place(x>>0, y>>0, game.gameGui.currentOrientation, {"player":null});
            game.gameGui.nbStructure++;
            break;
        case "kitchen":
            var next = game.gameGui.nbStructure;
            game.gameMap.structures["player0"][next] = new gamestructure("kit"+next, "kitchen", {"thorium":4}, {"food":4}, {"Cooker":2}, 30);
            game.gameMap.structures["player0"][next].place(x>>0, y>>0, game.gameGui.currentOrientation, {"player":null});
            game.gameGui.nbStructure++;
            break;
        case "defenceArea":
            var next = game.gameGui.nbStructure;
            game.gameMap.structures["player0"][next] = new gamestructure("defAre"+next, "defenceArea", {"thorium":4}, null, {"Soldier":4}, 100);
            game.gameMap.structures["player0"][next].place(x>>0, y>>0, game.gameGui.currentOrientation, {"player":null});
            game.gameGui.nbStructure++;
            break;
    }
}

gamegui.prototype.startDestructMode = function(){

}
gamegui.prototype.moveCursor = function(evt){
    if(game.gameGui.mouseUp === false){
        if(game.gameGui.constructMode == true && game.gameGui.currentType == "corridor"){
            //Retirer l'ancien path (graphiquement)
            for(var i in game.gameGui.currentConstructPath){
                game.mainContainer.removeChild(game.gameGui.currentConstructPath[i]);
                delete game.gameGui.currentConstructPath[i];
            }


            game.gameGui.currentConstruct.x = game.gameGui.initCellPos.x;
            game.gameGui.currentConstruct.y = game.gameGui.initCellPos.y;

            var currentCell = {};
            currentCell.x = evt.target.getAttribute('data-posx');
            currentCell.y = evt.target.getAttribute('data-posy');
            var curID = evt.target.id;
            currentCell.gridPos = curID.split('-');
            currentCell.gridPos[0] = currentCell.gridPos[0]>>0;
            currentCell.gridPos[1] = currentCell.gridPos[1]>>0;

            var startPlot = game.gameMap.convertGridCoordsToAStarCoords(game.gameGui.initCellPos.gridPos);
            var endPlot = game.gameMap.convertGridCoordsToAStarCoords(currentCell.gridPos);
            game.gameGui.constructPath = astar(game.gameMap.grid.pathGrid, startPlot, endPlot,0);
            game.gameGui.constructPathError = false;
            if(game.gameGui.constructPath.length == 0){
                game.gameGui.constructPath = astar(game.gameMap.grid.pathGrid, startPlot, endPlot,1);
                game.gameGui.constructPathError = true;
            }

            //copy shape cursor
            game.gameGui.currentConstructPath = [];
            for(var i in game.gameGui.constructPath){
                var canvasCoords = game.gameMap.convertGridCoordsToPlacementCoords(game.gameMap.convertAStarCoordsToGridCoords(game.gameGui.constructPath[i]));
                game.gameGui.currentConstructPath.push(game.gameRenderer.createCorridor(canvasCoords[0], canvasCoords[1], null,game.gameGui.constructPathError));
            }
        }
    }else{
        var o = evt.target;
        posx = o.getAttribute('data-posx');
        posy = o.getAttribute('data-posy');


        if (game.gameGui.needCursor) {
            game.gameGui.cursor1x1.x = posx;
            game.gameGui.cursor1x1.y = posy;
        }
        if (game.gameGui.constructMode) {
            game.gameGui.currentConstruct.x = posx;
            game.gameGui.currentConstruct.y = posy;
            //detecter si position correcte
        }

        if (game.gameGui.destructMode) {

        }
    }
}
gamegui.prototype.clickCursor = function(evt){
    evt.preventDefault();
    game.gameGui.mouseUp = true;
    switch (evt.which) {
        case 1://Left click
            if (game.gameGui.constructMode === true){
                if(game.gameGui.currentConstructPath.length) {
                    for (var i in game.gameGui.currentConstructPath) {
                        game.mainContainer.removeChild(game.gameGui.currentConstructPath[i]);
                        delete game.gameGui.currentConstructPath[i];
                    }
                }

                var o = evt.target;
                var ID = o.id;
                var coords = ID.split('-');
                game.gameGui.placeConstruct(coords[0], coords[1]);
                game.mainContainer.removeChild(game.gameGui.currentConstruct);
                game.gameGui.constructMode = false;
            }
            $('#cursor').attr('class',"pointer");
            $('body').attr('class',"pointer");
            $('#gamemap').off("mousemove");
            break;
        case 2://Middle click
            if(game.gameGui.constructMode === true && game.gameGui.currentType != "corridor"){
                game.gameGui.rotateConstruct(evt);
            }
            break;
        case 3://Right click
            if(game.gameGui.constructMode === true){
                game.gameGui.cancelBuild(evt);
            }
            break;
    }
}
gamegui.prototype.startDragCursor = function(evt){
    evt.preventDefault();
    game.gameGui.initCellNode = evt.target;
    game.gameGui.initCellPos.x = evt.target.getAttribute('data-posx');
    game.gameGui.initCellPos.y = evt.target.getAttribute('data-posy');
    var curID = evt.target.id;
    game.gameGui.initCellPos.gridPos = curID.split('-');
    game.gameGui.initCellPos.gridPos[0] = game.gameGui.initCellPos.gridPos[0]>>0;
    game.gameGui.initCellPos.gridPos[1] = game.gameGui.initCellPos.gridPos[1]>>0;

    game.gameGui.initMousePos.x = evt.clientX;
    game.gameGui.initMousePos.y = evt.clientY;
    game.gameGui.initStagePosition.x = game.mainContainer.x;
    game.gameGui.initStagePosition.y = game.mainContainer.y;
    if(game.gameGui.constructMode == true && game.gameGui.currentType == "corridor"){
        game.gameGui.mouseUp = false;
        $('#cursor').attr('class',"path_placing");
        $('body').attr('class',"path_placing");
    }else if(game.gameGui.constructMode == false){
        switch (evt.which) {
            case 1://Left click
                game.gameGui.mouseUp = false;
                $('#cursor').attr('class',"move");
                $('body').attr('class',"move");
                $('#gamemap').on('mousemove',function(evt){
                    if(game.gameGui.constructMode == false){//Move map
                        game.mainContainer.x = game.gameGui.initStagePosition.x - (game.gameGui.initMousePos.x - evt.clientX)>>0;
                        game.mainContainer.y = game.gameGui.initStagePosition.y - (game.gameGui.initMousePos.y - evt.clientY)>>0;
                        var ratio;
                        switch(game.gameMap.zoom){
                            case 1: ratio = 0.25;break;
                            case 2: ratio = 0.5;break;
                            case 3: ratio = 1;break;
                            case 4: ratio = 2;break;
                        }
                        if(game.mainContainer.x < (-(game.gameMap.width * game.gameMap.tileWidth * ratio) + window.innerWidth)){
                            game.mainContainer.x = (-(game.gameMap.width * game.gameMap.tileWidth * ratio) + window.innerWidth);
                        }
                        if(game.mainContainer.x > 0){
                            game.mainContainer.x = 0;
                        }
                        if(game.mainContainer.y < (-(game.gameMap.height * game.gameMap.tileHeight * ratio) + window.innerHeight)){
                            game.mainContainer.y = (-(game.gameMap.height * game.gameMap.tileHeight * ratio) + window.innerHeight);
                        }
                        if(game.mainContainer.y > 0){
                            game.mainContainer.y = 0;
                        }
                        $('#gameBackground').css('left',game.mainContainer.x + "px").css('top',game.mainContainer.y + "px");

                        //DEBUG
                        if(game.gameDebug.debugGridGroup != undefined){
                            game.gameDebug.debugGridGroup.x = game.mainContainer.x;
                            game.gameDebug.debugGridGroup.y = game.mainContainer.y;
                            game.gameDebug.debugGridGroup.scaleX = game.mainContainer.scaleX;
                            game.gameDebug.debugGridGroup.scaleY = game.mainContainer.scaleY;
                        }

                        if(game.gameDebug.debugGridInfosGroup != undefined){
                            game.gameDebug.debugGridInfosGroup.x = game.mainContainer.x;
                            game.gameDebug.debugGridInfosGroup.y = game.mainContainer.y;
                            game.gameDebug.debugGridInfosGroup.scaleX = game.mainContainer.scaleX;
                            game.gameDebug.debugGridInfosGroup.scaleY = game.mainContainer.scaleY;
                        }

                        if(game.gameDebug.debugGridAStarGroup != undefined){
                            game.gameDebug.debugGridAStarGroup.x = game.mainContainer.x;
                            game.gameDebug.debugGridAStarGroup.y = game.mainContainer.y;
                            game.gameDebug.debugGridAStarGroup.scaleX = game.mainContainer.scaleX;
                            game.gameDebug.debugGridAStarGroup.scaleY = game.mainContainer.scaleY;
                        }
                    }
                });
            case 2://Middle click
                break;
            case 3://Right click
                break;
        }
    }
}
gamegui.prototype.cancelBuild = function(evt){
    evt.preventDefault();
    game.mainContainer.removeChild(game.gameGui.currentConstruct);
    if(game.gameGui.constructMode == true && game.gameGui.currentType == "corridor") {
        //Retirer l'ancien path (graphiquement)
        for (var i in game.gameGui.currentConstructPath) {
            game.mainContainer.removeChild(game.gameGui.currentConstructPath[i]);
            delete game.gameGui.currentConstructPath[i];
        }
    }
    game.gameGui.constructMode = false;
}
gamegui.prototype.rotateConstruct = function(evt){
    if(game.gameGui.currentType != "corridor") {
        evt.preventDefault();
        switch (game.gameGui.currentOrientation) {
            case "N":
                game.gameGui.currentOrientation = "E";
                break;
            case "E":
                game.gameGui.currentOrientation = "S";
                break;
            case "S":
                game.gameGui.currentOrientation = "W";
                break;
            case "W":
                game.gameGui.currentOrientation = "N";
                break;
        }
        var coords = [game.gameGui.currentConstruct.x,game.gameGui.currentConstruct.y];
        game.mainContainer.removeChild(game.gameGui.currentConstruct);
        game.gameGui.startConstructMode(game.gameGui.currentType, coords);
    }
}
gamegui.prototype.haveRes = function(type, qty){

}
gamegui.prototype.removeRes = function(type, qty){

}
gamegui.prototype.addRes = function(type, qty){

}
